package wrapper

import (
	pb "emicro_test/emicro_9/grpc_gateway/pbfile"
	"github.com/afex/hystrix-go/hystrix"
)

//限流处理
func HystrixLimit(commandName, endpoint string, action func() error) error{

	var config hystrix.CommandConfig
	switch endpoint {
	case "UserService.UserLogin":			  //限制3秒内只能有2个并发连接
		config = hystrix.CommandConfig{
			Timeout: 3000,
			MaxConcurrentRequests: 2,

			//下面三个参数是熔断配置，也就是有RequestVolumeThreshold个请求，就判断超过ErrorPercentThreshold比例则熔断，熔断时间SleepWindow
			ErrorPercentThreshold: 25,        //错误率，百分比，超过设定值则打开熔断器，默认50(50%)
			RequestVolumeThreshold:2,         //请求阈值  熔断器是否打开首先要满足这个条件；这里的设置表示至少有2个请求才进行ErrorPercentThreshold错误百分比计算，默认20
			SleepWindow: 3000,                //过多长时间，熔断器再次检测是否开启（是否启动服务运行）。单位毫秒，默认5秒
		}
	case "UserService.UserReg":
		config = hystrix.CommandConfig{
			Timeout: 5000,
			MaxConcurrentRequests: 10,
			ErrorPercentThreshold: 25,
			RequestVolumeThreshold:10,
			SleepWindow: 2000,
		}
	default:
		config = hystrix.CommandConfig{
			Timeout: 5000,
			MaxConcurrentRequests: 10000,
			ErrorPercentThreshold: 25,
			RequestVolumeThreshold:100,
			SleepWindow: 5000,
		}
	}
	hystrix.ConfigureCommand(commandName, config)

	return hystrix.Do(commandName, func() error{
		return action()
	}, func(err error) error{
		return err
	})
}

//降级处理
func HystrixFallback(resp interface{}) {
	switch t:= resp.(type) {
	case *pb.RegResp:
		t.Status = 2
		t.Msg = "please wait to try"
	case *pb.LoginResp:
		t.Status = 2
		t.Msg = "please wait to try"
	case *pb.TestResp:
		t.Msg = "is limit"
	default:

	}
}

